package android.demo.engine.visitor;

import android.demo.engine.BusinessProcess;
import android.demo.engine.TaskGraph;
import android.demo.engine.tasks.ActivityTask;
import android.demo.engine.tasks.ContentProviderTask;
import android.demo.engine.tasks.ServiceTask;
import android.demo.engine.tasks.Task;

public class BackHandlerVisitor implements TaskVisitor {

	private BusinessProcess process;
	
	private ActivityTask result;
	
	public BackHandlerVisitor(BusinessProcess businessProcess) {
		this.process= businessProcess;
	}
	
	public ActivityTask getResult(){
		return result;
	}
	
	private void goBack(Task previous) {
		previous.init();
		TaskGraph tasks= process.getTasks();
		if(tasks.hasPrevious(previous))
			tasks.getPreviousTask(previous).accept(this);
	}

	@Override
	public void visit(ActivityTask activityTask) {
		if(process.isCurrentTask(activityTask) || !activityTask.hasResult())
			goBack(activityTask);
		else{
			activityTask.init();
			result= activityTask;
		}
	}

	@Override
	public void visit(ServiceTask serviceTask) {
		goBack(serviceTask);
	}


	@Override
	public void visit(ContentProviderTask contentProviderTask) {
		goBack(contentProviderTask);
	}

}
